package com.apptonelabs.android.util;

import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.TimeZone;

import android.content.Context;
import android.database.Cursor;
import android.net.ParseException;

public class TimeUtil {
	public static Long persistDate(Date date) {
	    if (date != null) {
	        return date.getTime();
	    }
	    return null;
	}
	
	public static Date loadDate(Cursor cursor, int index) {
	    if (cursor.isNull(index)) {
	        return null;
	    }
	    return new Date(cursor.getLong(index));
	}
	
	public static String formatDateTime(Context context, String timeToFormat)
			throws java.text.ParseException {

		String finalDateTime = "";
		SimpleDateFormat iso8601Format = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");

		Date date = null;
		if (timeToFormat != null) {
			try {
				date = iso8601Format.parse(timeToFormat);
			} catch (ParseException e) {
				date = null;
			}

			if (date != null) {
				long when = date.getTime();
				int flags = 0;
				flags |= android.text.format.DateUtils.FORMAT_SHOW_TIME;
				flags |= android.text.format.DateUtils.FORMAT_SHOW_DATE;
				flags |= android.text.format.DateUtils.FORMAT_ABBREV_MONTH;
				flags |= android.text.format.DateUtils.FORMAT_SHOW_YEAR;

				finalDateTime = android.text.format.DateUtils.formatDateTime(
						context, when + TimeZone.getDefault().getOffset(when),
						flags);
			}
		}
		return finalDateTime;
	}
	
	public static long date2long(String dateToFormat)
			throws java.text.ParseException {
		
		dateToFormat = dateToFormat + " 00:00:00";

		SimpleDateFormat iso8601Format = new SimpleDateFormat("dd-MM-yyyy HH:mm:ss");

		Date date = null;
		if (dateToFormat != null) {
			try {
				date = iso8601Format.parse(dateToFormat);
			} catch (ParseException e) {
				date = null;
			}

			if (date != null) {
				long when = date.getTime();
				return when + TimeZone.getDefault().getOffset(when);
			}
		}
		
		return -1;
	}
}